package com.mcp.mcpserver.controller;

import com.alibaba.fastjson2.JSON;
import com.mcp.mcpserver.entity.DBRequestBody;
import com.mcp.mcpserver.model.McpRequest;
import com.mcp.mcpserver.model.McpResponse;
import com.mcp.mcpserver.service.DynamicQueryService;
import com.mcp.mcpserver.service.McpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author zhangxin569
 * @date 2025/8/6
 */
@Slf4j
@RestController
@RequestMapping("/mcp")
public class McpController {

    @Autowired
    private McpService mcpService;

    @Autowired
    private DynamicQueryService dynamicQueryService;

    @PostMapping("/execute")
    public ResponseEntity<McpResponse> execute(@RequestBody McpRequest request) {
        log.info("Received request: {}", request);
        McpResponse response = mcpService.handleRequest(request);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/executeQuery")
    public ResponseEntity<McpResponse> executeQuery(@RequestBody DBRequestBody dbRequestBody) {

        log.info("Received request for dbRequestBody : {}",
                JSON.toJSONString(dbRequestBody));
        log.debug("Received request for database instance: {}",
                dbRequestBody.getDatabaseInstance().getDbInstanceId());
        log.debug("SQL: {}", dbRequestBody.getSql());
        log.debug("Params: {}", dbRequestBody.getParams());

        try {
            McpResponse response = dynamicQueryService.executeQuery(
                    dbRequestBody.getDatabaseInstance(),
                    dbRequestBody.getSql(),
                    dbRequestBody.getParams()
            );

            log.info("Query executed successfully : {}",  JSON.toJSONString(response));
            return ResponseEntity.ok(response);
        } catch (SecurityException e) {
            log.warn("Security violation detected: {}", e.getMessage());
            return ResponseEntity.badRequest().body(
                    McpResponse.error("SECURITY_ERROR", e.getMessage())
            );
        } catch (IllegalArgumentException e) {
            log.warn("Invalid request: {}", e.getMessage());
            return ResponseEntity.badRequest().body(
                    McpResponse.error("INVALID_REQUEST", e.getMessage())
            );
        } catch (Exception e) {
            log.error("Error processing request", e);
            return ResponseEntity.internalServerError().body(
                    McpResponse.error("SERVER_ERROR", "Internal server error: " + e.getMessage())
            );
        }
    }
}